<?php
/**
 * Created by PhpStorm.
 * User: cephei
 * Date: 12/24/15
 * Time: 1:50 PM
 */

namespace Plugins\ZhanqiSign;

use Core\PluginContainer;

class Plugin_ZhanqiSign
{
    private $db;

    public function __construct()
    {
        $this->db = PluginContainer::getInstance()->singletonMake('database');
    }


    public function doScan()
    {

        $userList = $this->db->get("select * from plg_zhanqi_users");
        foreach ($userList as $user) {
            $this->scanFollow($user->userid,$user->zqguid);
        }
    }

    public function doSign()
    {

        $userList = $this->db->get("select * from plg_zhanqi_users");
        foreach ($userList as $user) {
            $this->signWeb($user->userid,$user->zqguid);
        }
    }

    public function scanFollow($userId,$zqGUID)
    {
        $curl = PluginContainer::getInstance()->make('curl');
        $curl->cookies = ["ZQ_GUID" => $zqGUID];
        $response = $curl->sendRequest("http://www.zhanqi.tv/api/user/follow.listall");
        $json = json_decode($response);
        if ($json->code == 0) {
            foreach ($json->data as $item) {
                if($this->db->first("select count(*) from plg_zhanqi_follows where userid=$userId and roomid=$item->roomId")->c<=0){
                    $this->db->insert("plg_zhanqi_follows",["name"=>$item->title,
                        "nickname"=>$item->nickname,
                        "roomurl"=>$item->roomUrl,
                        "roomid"=>$item->roomId,
                        "userid"=>$userId
                    ]);
                }
            }
        }
    }

    public function signWeb($userId,$zqGUID){
        $date = date('Y-m-d',time());
        $followList = $this->db->get("select * from plg_zhanqi_follows where userid=$userId and signtime<'$date'");
        foreach($followList as $follow) {
            $curl = PluginContainer::getInstance()->make('curl');
            $curl->cookies = ["ZQ_GUID" => $zqGUID];
            $curl->formData = ["roomId" => $follow->roomid];
            $curl->method = "POST";
            $response = $curl->sendRequest("http://www.zhanqi.tv/api/actives/signin/fans.status");
            if (json_decode($response)->code == 0) {
                $curl->sendRequest("http://www.zhanqi.tv/api/actives/signin/fans.sign");
                $this->db->update("plg_zhanqi_follows", ["signtime" => $date], " where roomid=$follow->roomid and userid=$userId");
            }
        }
    }
}